<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/imPort')"
          >excel导入</el-button>
          <el-button type="danger" size="small" @click="expotExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop: 'timeOfEntry', order: 'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="员工头像" width="100">
            <template #default="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="width:100%"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <!-- 过滤器 -->
            <template #default="{row}">
              {{ formatData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?userId=${row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :current-page="page"
            :page-size="size"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog
        v-if="showDialog"
        title="新增员工"
        :visible.sync="showDialog"
      >
        <addEmployees @close="showDialog= false" @success="hSuccess" />
      </el-dialog>
      <!-- 生成二维码图片 -->
      <el-dialog
        title="生成二维码"
        :visible.sync="showCodeDialog"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import addEmployees from '@/views/employees/empDialog.vue'
import employeesEnum from '@/constant/employees'
import { getEmployee, delEmployees } from '@/api/employees'
// 使用find方法实现正式工非正式工区别
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// console.log(hireType, 'hireType')
// 使用reduce方法实现正式工非正式工区别
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  name: 'VueHrEmployees',
  components: {
    addEmployees
  },
  data() {
    return {
      showCodeDialog: false,
      showDialog: false,
      list: [],
      page: 1,
      size: 10,
      total: 0
    }
  },
  created() {
    this.loadEmployee()
  },
  methods: {
    showCode(url) {
      if (url) {
        this.showCodeDialog = true
        // dom更新的是异步的
        this.$nextTick(() => {
          const canvas = this.$refs.myCanvas
          QRCode.toCanvas(canvas, url)
        })
      } else {
        this.$message.error('请输入正确图片')
      }
    },
    expotExcel() {
      const { Theader, data } = this.tranZhkeyToExcel(this.list)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: Theader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        // this.downloadLoading = false
      })
    },
    // 封装导出
    tranZhkeyToExcel(list) {
      // 中引文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 生成表头
      const one = list[0]
      if (!one) return
      const Theader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })
      const data = list.map(item => {
        return Object.values(item)
      })
      // console.log('data',data)
      return { Theader, data }
    },
    // 删除
    async hDel(id) {
      console.log(id)
      const res = await delEmployees(id)
      // console.log(res, 'hahah')
      if (res.code === 10000) {
        this.$message.success(res.message)
        if (this.list.length === 1) {
          this.page--
          if (this.page === 0) {
            this.page = 1
          }
        }
      }
      this.loadEmployee()
    },
    // 添加之后 重新渲染页面  并且跳转到最后一页
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployee()
      this.showDialog = false
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployee()
    },
    //  把后端传送过来的数字 转换为数据
    formatData(id) {
      // 使用find方法实现正式工非正式工区别 但是消耗性能特别多
      // return employeesEnum.hireType.find(item => item.id === id).value
      return hireType[id]
    },
    async loadEmployee() {
      try {
        // console.log({ page: this.page, size: this.size })
        const res = await getEmployee({ page: this.page, size: this.size })
        // console.log(res, 'hah')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
